import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { home as homeApi, common as api, noClass as noClassApi } from '../api/const'
import request from '../api/request';

export interface State {
  storeList: any;
  storeVo: any
}

export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    storeList: [],
    storeVo: {}
  },
  getters: {
    getStoreId: (state) => {
      return state.storeVo.id
    }
  },
  mutations: {
    SET_STORE_LIST(state, list) {
      state.storeList = list || []
    },
    SET_STORE(state, store) {
      state.storeVo = store
    }
  },
  actions: {
    getStoreList({state, commit}, data?) {
      const params = { storeId: state?.storeVo?.id || uni.getStorageSync('storeVo')?.id || '', ...data };
      const requestOptions = {
        path: homeApi.getAllStoreList,
        method: 'post',
        data: params,
        hideLoading: true,
        closeErrBox: true,
      };
      request<any>(requestOptions).then((res) => {
        if (res.code === 200) {
          commit('SET_STORE_LIST', res.data.storeVos);
          commit('SET_STORE', res.data.storeVo);
        } else {
          commit('SET_STORE_LIST');
        }
      })
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
